package com.kma.ncpractice2013.servlets;

import com.kma.ncpractice2013.dao.PromoCodeDAO;
import com.kma.ncpractice2013.model.PromoCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

/**
 * User: Illyas
 * Date: 12/7/13
 * Time: 1:08 PM
 */

public class PromoCodeServlet extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        // checks if the promocode exists
        if (action.equals("checkCode"))
        {
            String sCode = request.getParameter("code");
            PromoCodeDAO dao = new PromoCodeDAO();
            PromoCode code = dao.getByCode(sCode);
	        Date d = new Date(System.currentTimeMillis());
	        if (code==null || code.getUsed()==1 || code.getStartDate().after(d) || code.getExpirationDate().before(d) )
	        {
				out.print("Invalid code");
		        return;
	        }
            //String reply = (code != null) ? String.valueOf(code.getDiscount()) : "DOES NOT REALLY MATTER";
            out.print(code.getDiscount());
        }
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

	}
}
